package com.xian.tszs.meal.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import com.alibaba.druid.util.StringUtils;
import com.xian.tszs.meal.dto.OrderAndConup;
import com.xian.tszs.meal.dto.OrderGenerate;
import com.xian.tszs.meal.dto.TsOrderDTO;
import com.xian.tszs.meal.entity.OrderGoodsRel;
import com.xian.tszs.meal.entity.TsGoods;
import com.xian.tszs.meal.entity.TsOrder;
import com.xian.tszs.meal.entity.TsUser;
import com.xian.tszs.meal.entity.UrCouponRel;
import com.xian.tszs.meal.enums.OrderStatusEnum;
import com.xian.tszs.meal.enums.PayMentStatus;
import com.xian.tszs.meal.mapper.TsGoodsMapper;
import com.xian.tszs.meal.mapper.TsOrderMapper;
import com.xian.tszs.meal.mapper.UrCouponRelMapper;
import com.xian.tszs.meal.repository.OrderGoodsRelRepository;
import com.xian.tszs.meal.repository.TsGoodsRepository;
import com.xian.tszs.meal.repository.TsOrderRepository;
import com.xian.tszs.meal.service.FrontOrderService;
import com.xian.tszs.meal.utils.DoubleUtil;
import com.xian.tszs.meal.utils.UUIDUtils;
import com.xian.tszs.utils.DateUtils;
import com.xian.tszs.utils.RandomUtils;

@Service
public class FrontOrderServiceImpl implements FrontOrderService {

	@Autowired
	private TsGoodsRepository tsGoodsRep;

	
	@Autowired
	private TsGoodsMapper tsGoodsMapper;
	
	@Autowired
	private OrderGoodsRelRepository orderGoodsRep;
	
	@Autowired
	private TsOrderRepository tsOrderRep;

	@Autowired
	private StringRedisTemplate stringRedisTemplate;
	
	@Autowired
	private TsOrderMapper tsOrderMapper;
	
	@Autowired
	private UrCouponRelMapper urCouponRelMapper;
	
	@Override
	public String generateOrder(TsUser u, OrderGenerate orderGenerate) {
		TsOrder order = new TsOrder();
	 	boolean isHas =  stringRedisTemplate.hasKey("busi"+orderGenerate.getBusinessId());
	 	if (isHas) {
	 		//存在
	 		Integer orderSort = Integer.valueOf(stringRedisTemplate.opsForValue().get("busi"+orderGenerate.getBusinessId()));
	 		order.setOrderSort(orderSort+1);
	 		stringRedisTemplate.boundValueOps("busi"+orderGenerate.getBusinessId()).increment(1);//val +1
	 	} else {
	 		stringRedisTemplate.opsForValue().set("busi"+orderGenerate.getBusinessId(), "1",60*60,TimeUnit.SECONDS);//向redis里存入数据和设置缓存时间  
	 		order.setOrderSort(1);
	 	}
		// 生成订单
		order.setId(UUIDUtils.getUUID());
		order.setUserId(u.getId());
		order.setCouponAmount(0.00);
		order.setRemarks(orderGenerate.getRemarks());
		Double orderAmount = 0.00;
		int sort = 0;
		List<OrderGoodsRel> list = new ArrayList<OrderGoodsRel>();
		
		
		for (OrderAndConup oAc : orderGenerate.getGoods()) {
			// 遍历商品 新增到订单详情表
			// 生成订单详情
			OrderGoodsRel goodsRel = new OrderGoodsRel();
			goodsRel.setId(UUIDUtils.getUUID());
			goodsRel.setNum(oAc.getNum());
			TsGoods g = tsGoodsRep.findById(oAc.getId()).get();
			goodsRel.setGoodsId(g.getId());
			goodsRel.setSpecification(oAc.getSpecification());
			goodsRel.setSpecificationName(oAc.getSpecificationName());
			goodsRel.setActualPrice(g.getPrice());
			goodsRel.setOrderId(order.getId());
			goodsRel.setCreateTime(new Date());
			goodsRel.setSort(sort++);
			list.add(goodsRel);
			orderAmount = DoubleUtil.add(orderAmount, g.getPrice()*oAc.getNum());
			
			tsGoodsMapper.updateSalesVolume(oAc.getNum(),g.getId());	
		}
		
		orderGoodsRep.saveAll(list);
		//优惠券减免
		if (!StringUtils.isEmpty(orderGenerate.getCouponId())) {
			
			UrCouponRel urCouponRel = urCouponRelMapper.findById(orderGenerate.getCouponId());
			
			Date end = DateUtils.getTodayDate();
			
			if (urCouponRel != null && orderAmount >= urCouponRel.getCoupon()&& urCouponRel.getUsed() == 1 && urCouponRel.getEndDate().getTime()>=end.getTime()) {
				//达到优惠使用条件
				orderAmount = DoubleUtil.sub(orderAmount, urCouponRel.getSubtract());
				//修改这个优惠券已经被使用
				urCouponRelMapper.updateUrCouponRelUsed(order.getId(), urCouponRel.getId());
				//订单减免金额
				order.setCouponAmount(urCouponRel.getSubtract());
			}
			
		}
		order.setOrderAmount(orderAmount);
		order.setBusinessId(orderGenerate.getBusinessId());
		order.setCreateTime(new Date());
		order.setOrderStatus(OrderStatusEnum.WAIT.getValue());//暂时下单后直接是已付款状态
		order.setPaymentStatus(PayMentStatus.PAY_NO.getValue());
		
		String orderNumber = DateUtils.getNowDatetoString()+RandomUtils.generateNum(20);
		order.setOrderNumber(orderNumber);
		tsOrderRep.save(order);
		
		return orderNumber;
	}

	@Override
	public List<TsOrderDTO> findUserOrder(String status, String uId) {
		
		return tsOrderMapper.findUserOrder(status,uId);
	}

	@Override
	public void cancelOrder(String id) {
		tsOrderMapper.updateOrderStatus(OrderStatusEnum.CLOSE.getValue(), id);
	}

}
